package main

import (
	"encoding/base64"
	"fmt"
	"log"
	"net/http"
	"time"
)

/**
 * 设置cookie
 */
func setCookie(w http.ResponseWriter, r *http.Request) {
	c1 := http.Cookie{
		Name:"p_skey",
		Value:"e620c791f8cd282f9ffb30acf1719068",
		HttpOnly:true,
	}

	c2 := http.Cookie{
		Name:"skey",
		Value:"551472e81eb11d07ccb44a3a91549539",
		HttpOnly:true,
	}

	http.SetCookie(w, &c1)
	http.SetCookie(w, &c2)
}

/**
 * 读取cookie
 */
func getCookie(w http.ResponseWriter, r *http.Request)  {
	p_skey, err := r.Cookie("p_skey")
	if err != nil {
		log.Fatal(err)
	}

	cookies := r.Cookies()

	//不加 .value p_skey=e620c791f8cd282f9ffb30acf1719068
	// .value  e620c791f8cd282f9ffb30acf1719068 获取cookie的值
	// .Name   p_skey 获取Cookie的名称
	fmt.Fprintln(w, p_skey.Name)
	fmt.Fprintln(w, p_skey.Value)
	//[p_skey=e620c791f8cd282f9ffb30acf1719068 skey=551472e81eb11d07ccb44a3a91549539]
	fmt.Fprintln(w, cookies)
}

/**
 * 设置闪现消息
 */
func setMsg(w http.ResponseWriter, r *http.Request) {
	//将闪现消息设置成byte切片的目的是为了给base64编码使用
	msg := []byte("hello world")
	c := http.Cookie{
		Name:"msg",
		Value:base64.URLEncoding.EncodeToString(msg),
	}
	http.SetCookie(w, &c)
}

/**
 * 读取闪现消息
 */
func getMsg(w http.ResponseWriter, r *http.Request) {
	c, err := r.Cookie("msg")
	if err != nil {
		fmt.Fprintln(w, "msg not found")
	} else {
		// MaxAge=0 默认，当浏览器关闭就会删除
		// MaxAge<0 立即删除
		// MaxAge>0 指定单位秒后删除
		// time.Unix(0, 1) 1970-01-01 08:00:00.000000001 +0800 CST 把秒数转换成具体的时间，从1970/1/1 8点开始算
		rc := http.Cookie{
			Name:"msg",
			MaxAge:-1,
			Expires:time.Unix(0, 1),
		}
		http.SetCookie(w, &rc)
		fmt.Fprintln(w, time.Unix(10000, 1))
		val, err := base64.URLEncoding.DecodeString(c.Value)
		if err != nil {
			fmt.Fprintln(w, "msg decode err")
		} else {
			fmt.Fprintln(w, string(val))
		}
	}
}

func main() {
	http.HandleFunc("/setCookie", setCookie)
	http.HandleFunc("/getCookie", getCookie)
	http.HandleFunc("/setMsg", setMsg)
	http.HandleFunc("/getMsg", getMsg)

	svr := http.Server{
		Addr:"127.0.0.1:8080",
	}
	svr.ListenAndServe()
}
